package com.xiaolin.web.config;

import com.xiaolin.web.filter.HelloFilter;
import com.xiaolin.web.filter.SecondFilter;
import com.xiaolin.web.interceptor.HelloInterceptor;
import com.xiaolin.web.listener.HelloServletContextListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;

/**
 * @ClassName WebConfig
 * @Description TODO
 * @Detail 过滤器配置类，用于注册过滤器
 * @Author MyPC
 * @Date 2020/9/28
 * @Version 1.0
 */
@Configuration
public class WebConfig implements WebMvcConfigurer{
    @Autowired
    private HelloFilter helloFilter;

    @Autowired
    private SecondFilter secondFilter;

//    @Autowired
//    private HelloServletContextListener listener;

    @Autowired
    private HelloInterceptor interceptor;


    /**
     * 配置拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor)
                .addPathPatterns("/**");
    }

    /**
     * 配置过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean hello(){
        FilterRegistrationBean registrationBean=new FilterRegistrationBean();
        registrationBean.setFilter(helloFilter);
        ArrayList<String> list = new ArrayList<>();
        list.add("/*");
        //路径匹配方式，即配置哪些请求路径会被拦截,要求一个String类型的集合
        registrationBean.setUrlPatterns(list);
        //给过滤器取名字
        registrationBean.setName("helloFil");
        //设置过滤器的先后顺序，数字小就靠前
        registrationBean.setOrder(2);
        return registrationBean;
    }

    /**
     * 配置监听器
     * @return
     */
    @Bean
    public FilterRegistrationBean second(){
        FilterRegistrationBean registrationBean=new FilterRegistrationBean();
        registrationBean.setFilter(secondFilter);
        ArrayList<String> list = new ArrayList<>();
        list.add("/*");
        registrationBean.setUrlPatterns(list);
        registrationBean.setName("second");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    /**
     * 配置监听器
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean listenerRegistrationBean(){
        ServletListenerRegistrationBean listenerRegistrationBean=new ServletListenerRegistrationBean();
        //可以使用@Component注解注入，也可以手动创建一个
        listenerRegistrationBean.setListener(new HelloServletContextListener());
        return listenerRegistrationBean;
    }

}
